<!--  -->
<template>
  <div class="" style="min-width: 1440px">
    <el-card>
      <div class="horoscope-list">
        <span class="fs-18">交易查询</span>
        <vab-icon class="icon" icon="close-fill" />
      </div>
      <el-divider />
      <el-form ref="form" label-position="top" :model="formData" :rules="rules">
        <div>
          <div class="pb-20">
            <div class="fs-14 lh-20 mt-24 c-333">持有人方式</div>
            <el-form-item class="mb-0 mt-20">
              <el-radio-group
                v-model="formData.uniTypeValue"
                size="medium"
                @input="uniTypeChange"
              >
                <el-radio
                  v-for="(item, index) in uniType"
                  :key="index"
                  border
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <div class="fs-14 lh-20 mt-24 c-333">卡段</div>
            <el-form-item class="mb-0 mt-20" prop="cardBin">
              <el-radio-group
                v-model="formData.cardBin"
                size="medium"
                @input="cardTypeChange"
              >
                <el-radio
                  v-for="(item, index) in cardType"
                  :key="index"
                  border
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <div v-show="cardBinInfo.open_fee" style="line-height: 50px">
              <span class="span_block">
                开卡费:$ {{ cardBinInfo.open_fee }}
              </span>
              <span class="span_block">
                充值费率:{{ cardBinInfo.charge_fee_rate }}%
              </span>
              <span class="span_block">
                退款费率:{{ cardBinInfo.refund_fee_rate }}%
              </span>
            </div>
            <div class="fs-14 lh-20 mt-24 c-333">开卡方式</div>
            <el-form-item class="mb-0 mt-20" prop="open_type">
              <el-radio-group
                v-model="formData.open_type"
                size="medium"
                @input="openTypeChange"
              >
                <el-radio
                  v-for="(item, index) in openType"
                  :key="index"
                  border
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 必填、选填信息 -->
          <div v-if="formData.open_type == '1'">
            <div v-if="formData.uniTypeValue == '1'">
              <div>
                <div
                  style="
                    position: relative;
                    left: -330px;
                    width: 1140px;
                    border-top: 1px dashed rgb(225, 227, 228);
                  "
                ></div>
              </div>
              <div class="lh-16 fs-16 ff-bold fw-700 c-dark mt-40 mb-40">
                必填信息
              </div>
              <div class="mb-30">
                <div class="fs-14 lh-2">
                  <span>
                    <div class="d-flex">
                      <div>
                        <span>持卡人姓名</span>
                      </div>
                      <div class="mr-auto"></div>
                      <div
                        v-if="false"
                        class="fs-14 lh-20 c-theme-link cursor-pointer"
                      >
                        <span>持卡人为开户法代</span>
                      </div>
                    </div>
                  </span>
                </div>
                <el-form-item class="mb-0 mt-12" prop="firstName">
                  <el-dropdown
                    popper-class="width-full-popper"
                    :teleported="false"
                    trigger="hover"
                  >
                    <div class="" style="overflow: hidden">
                      <el-input
                        v-model="formData.firstName"
                        class="input-004 input-004--border input-004--normal w-480"
                        placeholder="持卡人姓氏"
                        style="float: left; margin-right: 20px"
                      />
                      <el-input
                        v-model="formData.lastName"
                        class="input-004 input-004--border input-004--normal w-480"
                        placeholder="持卡人名字"
                        style="float: left"
                      />
                    </div>

                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in cardType"
                          :key="index"
                          :command="item.value"
                        >
                          {{ item.label }}
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-form-item>
              </div>

              <div class="fs-14 lh-20 mt-28">持卡人手机号</div>
              <el-form-item class="mb-28 mt-12" prop="mobile">
                <div class="d-flex">
                  <el-input
                    v-model="formData.mobile"
                    class="input-004 input-004--border input-004--normal w-480"
                    placeholder="请输入对方注册时使用的手机号"
                    type="number"
                  />
                </div>
              </el-form-item>
              <div class="fs-14 lh-20 mt-28">卡片地址</div>
              <el-form-item class="mt-20" prop="billingCity">
                <div class="d-flex">
                  <el-input
                    v-model="formData.billingCity"
                    class="input-004 input-004--border input-004--normal w-480"
                    placeholder="United States of America"
                  />
                </div>
              </el-form-item>

              <el-form-item class="mt-12" prop="billingState">
                <div class="d-flex">
                  <el-input
                    v-model="formData.billingState"
                    class="input-004 input-004--border input-004--normal w-480"
                    placeholder="State/Province/Region"
                  />
                </div>
              </el-form-item>

              <el-form-item class="mt-12" prop="billingZipCode">
                <div class="d-flex">
                  <el-input
                    v-model="formData.billingZipCode"
                    class="input-004 input-004--border input-004--normal w-480"
                    placeholder="ZIP Code"
                    type="number"
                  />
                </div>
              </el-form-item>
              <el-form-item class="mb-28 mt-12" prop="billingAddress">
                <div class="d-flex">
                  <el-input
                    v-model="formData.billingAddress"
                    class="input-004 input-004--border input-004--normal w-480"
                    placeholder="Address Line 1"
                  />
                </div>
              </el-form-item>
            </div>
            <div
              class="mt-40 mb-40"
              style="
                position: relative;
                left: -330px;
                width: 1140px;
                border-top: 1px dashed rgb(225, 227, 228);
              "
            ></div>
            <div class="h-16 lh-16 fs-16 ff-bold fw-700 c-dark">选填信息</div>
            <div class="fs-14 lh-20 mt-30">卡片标签</div>
            <el-form-item class="mb-0 mt-12" prop="cardAlias">
              <el-input
                v-model="formData.cardAlias"
                class="input-004 input-004--normal input-004--border w-480"
                placeholder="请输入卡标签（选填）"
              />
            </el-form-item>
            <div class="w-480 lh-16 fs-12 c-868e94 mt-8">
              <span>此项选填，用于记录卡片用途、管理卡片分组等</span>
            </div>
            <!--<div class="fs-14 lh-20 mt-28">地址二</div>
        <el-form-item class="mb-0 mt-12" prop="address2">
          <div class="d-flex">
            <el-input
              placeholder="Address Line 2"
              v-model="formData.address2"
              class="input-004 input-004&#45;&#45;border input-004&#45;&#45;normal w-480"
            ></el-input>
          </div>
        </el-form-item>-->
          </div>

          <!-- 上传批量开卡 -->
          <div v-else>
            <div>
              <div>
                <div class="h-40"></div>
                <div
                  style="
                    position: relative;
                    left: -330px;
                    width: 1140px;
                    border-top: 1px dashed rgb(225, 227, 228);
                  "
                ></div>
                <div class="h-40"></div>
              </div>
            </div>

            <div>
              <div class="fs-14 lh-20 fw-600 c-031520">
                <span>上传批量开卡信息</span>
              </div>
              <div>
                <el-form-item class="mb-0 mt-28">
                  <div class="w-480">
                    <div class="upload-004 before-upload is-vertical">
                      <el-upload
                        ref="upload"
                        action="#"
                        class="upload-demo"
                        drag
                        :file-list="batchList"
                        :http-request="uploadFile"
                        :limit="1"
                        :multiple="false"
                        :on-remove="handleRemoveFile"
                        show-file-list
                      >
                        <div>
                          <div
                            class="upload-004__trigger"
                            style="
                              width: 100%;
                              height: 120px;
                              min-height: 120px;
                            "
                          >
                            <div class="upload-004--before-upload">
                              <i
                                class="el-icon-upload"
                                style="color: #3eaeb4"
                              ></i>
                              <div class="upload-004__upload-hint">
                                <span>选择文件上传，</span>
                                或将文件拖拽到此处
                              </div>
                            </div>
                          </div>
                        </div>
                      </el-upload>
                    </div>
                  </div>
                </el-form-item>
                <div class="h-16"></div>
                <div class="lh-20 fs-14 c-brand">
                  <a download :href="excelTemplateSrc">下载导入文件模版</a>
                </div>
              </div>
              <!-- <div v-else>
                    <div class="h-16"></div>
                    <div class="w-480 d-flex fs-14 lh-20">
                      <span>
                        上传完成，解析成功数据{{ uploadSuccessNum }}条，
                        <span class="c-theme-orange">
                          解析失败{{ uploadFailNum }}条
                        </span>
                      </span>
                    </div>
                    <div class="h-16"></div>

                    <div class="w-480 d-flex fs-14 lh-20">
                      <el-button link type="primary" size="small">
                        重新上传
                      </el-button>
                      <div class="w-28"></div>
                      <el-button link type="primary" size="small">
                        查看表格
                      </el-button>
                    </div>
                  </div> -->
            </div>
          </div>

          <div>
            <div class="h-40"></div>
            <div
              style="
                position: relative;
                left: -330px;
                width: 1140px;
                border-top: 1px dashed rgb(225, 227, 228);
              "
            ></div>
            <div class="h-40"></div>
          </div>

          <div>
            <template v-if="unShow.indexOf('pay') === -1">
              <div>
                <div class="fs-14 lh-20">
                  <span>充值金额(USD)</span>
                </div>
                <div class="h-12"></div>
                <el-form-item class="mb-0" prop="chargeMoney">
                  <el-input
                    v-model="formData.chargeMoney"
                    class="input-004 input-004--border input-004--normal w-480"
                    :clearable="false"
                    type="Number"
                    @blur="getAllCardFee"
                  >
                    <template #append>USD</template>
                  </el-input>
                </el-form-item>
              </div>
              <div class="h-28"></div>
            </template>

            <div>
              <div class="fs-14 lh-20">
                <span>开卡数</span>
              </div>
              <div class="h-12"></div>
              <el-form-item class="mb-0" prop="num">
                <el-input
                  v-model="formData.num"
                  class="input-004 input-004--border input-004--normal w-480"
                  :clearable="false"
                  :disabled="disableNum"
                  type="Number"
                >
                  <template #append>张</template>
                </el-input>
              </el-form-item>
              <div class="h-8"></div>
              <div class="d-flex w-480">
                <div class="fs-12 lh-6 color-gray">
                  <span>单次批量最多可开50张</span>
                </div>
                <div class="mr-auto"></div>
                <div class="fs-14">
                  <span>剩余可开卡数:</span>
                  <span>{{ infoDetail.card_remain }}</span>
                </div>
              </div>
            </div>
            <div class="h-28"></div>

            <template v-if="unShow.indexOf('totalPay') === -1">
              <div class="w-480 d-flex fs-14 lh-20">
                <span>总充值金额</span>
                <div class="mr-auto"></div>
                <div>{{ formData.chargeMoney }} USD</div>
              </div>
              <div class="h-28"></div>
            </template>
            <div>
              <div class="w-480 d-flex fs-14 lh-20">
                <span>开卡费</span>
                <div class="mr-auto"></div>
                <div>{{ playMoney.open_fee }} USD</div>
              </div>
            </div>
            <div class="h-24"></div>
            <div>
              <div class="w-480 d-flex fs-14 lh-20">
                <span>充值手续费</span>
                <div class="mr-auto"></div>
                <div>{{ playMoney.charge_fee }} USD</div>
              </div>
              <div class="h-12" style="display: none"></div>
              <div
                class="w-480 fs-12 lh-16 c-error text-align-end"
                style="display: none"
              >
                <span>开卡服务费将在分组创建后，自动在分组预算中扣除</span>
              </div>
            </div>
            <div class="h-24"></div>

            <div class="w-480 d-flex fs-14 lh-20">
              <span>总费用</span>
              <div class="mr-auto"></div>
              <div class="fs-18 lh-28 fw-600 c-theme-black-1">
                {{ playMoney.total }} USD
              </div>
            </div>
          </div>
        </div>

        <el-button
          class="button-004 button-004--primary button-004--large mt-20"
          style="margin: 0 auto"
          type="purple"
          @click="submit"
        >
          确认新增
        </el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
  import {
    getCardBinds,
    getCardBinDetail,
    getCardFee,
    importNoHoldExcel,
    importHoldExcel,
  } from '@/api/card'
  import { baseURL } from '@/config'
  import {
    checkEN,
    checkAlphaNumericOrSpace,
    checkAlphaOrSpace,
  } from '@/utils/regular.js'
  import { createUniqueId } from '@/utils'
  import { sendData, closewebsocket } from '@/utils/websocket'
  import { mapGetters } from 'vuex'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      const validateName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入持卡人英文姓名'))
        } else if (!checkEN(value)) {
          callback(new Error('持卡人姓名只能为英文'))
        } else {
          callback()
        }
      }
      // 校验手机号，只能为10位
      const validateMobile = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入10位电话号码'))
        } else if (value.length !== 10) {
          callback(new Error('请输入10位电话号码'))
        } else {
          callback()
        }
      }
      // 校验城市名
      const validateCity = (rule, value, callback) => {
        console.log('value', value)
        if (value === '') {
          callback(new Error('请输入城市名'))
        } else if (!checkAlphaOrSpace(value)) {
          callback(new Error('城市名只能包含英文或空格'))
        } else {
          callback()
        }
      }
      //  校验地址
      const validateAddress = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入地址'))
        } else if (!checkAlphaNumericOrSpace(value)) {
          callback(new Error('地址只能包含英文、空格或数字'))
        } else {
          callback()
        }
      }
      const validateNum = (rule, value, callback) => {
        // if (isValidedAccout.value) return callback()
        if (value === '') {
          callback(new Error('请输入开卡数'))
        } else if (value < 1 || value > 50) {
          callback(new Error('开卡数应在1~50'))
        } else if (value > this.infoDetail.card_remain) {
          callback(new Error('剩余可开卡数不足'))
        } else {
          callback()
          // computedMoney().then(() => {
          //     isValidedAccout.value = true;
          //     form.value.validateField(['chargeMoney']);
          //     callback()
          // }).catch((error) => {
          //     callback(new Error(error))
          // })
        }
      }
      const validateMoney = (rule, value, callback) => {
        // if (isValidedAccout.value) return callback()
        if (value === '') {
          callback(new Error('请输入充值金额'))
        } else if (value <= 10) {
          callback(new Error('充值金额必须大于 10USD'))
        } else {
          // callback()
          // this.getAllCardFee()
          callback()
          // .then(() => {
          //   // isValidedAccout.value = true
          //   // form.value.validateField(['num'], () => {});
          //   callback()
          // })
          // .catch((error) => {
          //   callback(new Error(error))
          // })
        }
      }
      //这里存放数据
      return {
        formData: {
          type: '1',
          uniTypeValue: null,
          cardBin: '',
          open_type: '1',
          chargeMoney: 0,
          num: 1,
          cardAlias: '',
          binRangeId: '',
          firstName: '',
          lastName: '',
          mobile: '',
          billingCity: '',
          billingState: '',
          billingZipCode: '',
          billingAddress: '',
          address2: '',
          unique: '',
        },
        uniType: [
          {
            label: '实名卡',
            value: '1',
          },
          {
            label: '匿名卡',
            value: '2',
          },
        ],
        rules: {
          firstName: [{ validator: validateName, trigger: ['blur', 'change'] }],
          lastName: [{ validator: validateName, trigger: ['blur', 'change'] }],
          mobile: [{ validator: validateMobile, trigger: ['blur', 'change'] }],
          billingCity: [
            { validator: validateCity, trigger: ['blur', 'change'] },
          ],
          billingZipCode: [
            {
              required: true,
              message: '邮编为5位数字',
              trigger: ['blur', 'change'],
            },
          ],
          billingState: [
            {
              required: true,
              message: '2位英文缩写',
              trigger: ['blur', 'change'],
            },
          ],
          num: [{ validator: validateNum, trigger: ['blur'] }],
          chargeMoney: [{ validator: validateMoney, trigger: ['blur'] }],
          billingAddress: [
            { validator: validateAddress, trigger: ['blur', 'change'] },
          ],
        },
        cardBinInfo: {},
        cardType: [],
        openType: [
          {
            value: '1',
            label: '手动输入',
          },
          {
            value: '2',
            label: '批量导入',
          },
        ],
        unShow: [],
        disableNum: true,
        playMoney: {
          charge_fee: '0.00',
          open_fee: '0.00',
          total: '0.00',
        },
        batchList: [],
        isUpload: false,
        uploadSuccessNum: null,
        uploadFailNum: null,
      }
    },
    //监听属性 类似于data概念
    computed: {
      ...mapGetters({
        infoDetail: 'user/infoDetail',
      }),
      excelTemplateSrc() {
        let url = ''
        if (this.formData.uniTypeValue == 1) {
          // 有持卡人
          url = `${baseURL}/excel_template/批量开卡_持卡人.xlsx`
        } else {
          // 无持卡人
          url = `${baseURL}/excel_template/批量开卡(无持有人).xlsx`
        }
        return url
      },
    },
    //监控data中的数据变化
    watch: {},
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.formData.uniTypeValue = '1'
      this.getCardType()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    //方法集合
    methods: {
      toPage(item) {
        this.$router.push(item)
      },
      // 获取卡段
      async getCardType() {
        const { data } = await getCardBinds({
          type: this.formData.uniTypeValue,
        })
        if (data) {
          this.cardType =
            data.map((item) => ({
              label: item,
              value: item,
            })) || []
          this.formData.cardBin = this.cardType[0].value || ''
          this.formData.cardBin && this.getCardDetail()
        }
      },
      // 获取卡段详情
      async getCardDetail() {
        const { data } = await getCardBinDetail({
          cardbin: this.formData.cardBin,
        })
        if (data) {
          this.cardBinInfo = data || {}
        }
      },
      uniTypeChange(val) {
        this.formData.uniTypeValue = val
        this.getCardType()
      },
      cardTypeChange(val) {
        this.formData.cardBin = val
        this.getCardDetail()
      },
      openTypeChange(val) {
        this.formData.open_type = val
      },
      // 批量上传卡信息
      async uploadFile(file) {
        this.isUpload = true
        let formData = new FormData()
        formData.append('xls', file.file)
        if (this.formData.uniTypeValue == 1) {
          // 有持卡人
          const { data } = await importHoldExcel(
            this.formData.cardBin,
            formData
          )
          this.formData.num = data.card_num
          this.formData.unique = data.unique
          this.formData.chargeMoney = data.recharge_money
          this.playMoney.charge_fee = data.recharge_fee
          this.playMoney.open_fee = data.open_fee
          this.playMoney.total = data.total_money
          this.uploadSuccessNum = data.successNum
          this.uploadFailNum = data.failNum
        } else {
          // 无持卡人
          const { data } = await importNoHoldExcel(
            this.formData.cardBin,
            formData
          )
          console.log(data.unique)
          this.formData.num = data.card_num
          this.formData.unique = data.unique
          this.formData.chargeMoney = data.recharge_money
          this.playMoney.charge_fee = data.recharge_fee
          this.playMoney.open_fee = data.open_fee
          this.playMoney.total = data.total_money
          this.uploadSuccessNum = data.successNum
          this.uploadFailNum = data.failNum
        }
        this.batchList = [file.file]
        console.log(this.batchList)
      },
      handleRemoveFile() {
        this.batchList = []
        this.formData.num = 0
        this.formData.unique = ''
        this.formData.chargeMoney = 0
        this.playMoney.charge_fee = 0
        this.playMoney.open_fee = 0
        this.playMoney.total = 0
      },
      // 获取卡费
      async getAllCardFee() {
        let arr = {
          amount: this.formData.chargeMoney,
          cardbin: this.formData.cardBin,
        }
        const { data } = await getCardFee(arr)
        if (data) {
          this.playMoney = data
        } else {
          throw new Error(error)
        }
      },
      // 提交开卡
      submit() {
        let pack = {}
        let loading
        if (!this.formData.cardBin)
          return this.$baseMessage(
            `请选择卡段`,
            'error',
            'vab-hey-message-error'
          )
        if (this.formData.open_type !== '1' && !this.isUpload)
          return this.$baseMessage(
            `请上传开卡信息`,
            'error',
            'vab-hey-message-error'
          )
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.formData.uniTypeValue == 2) {
              // 无持卡人
              if (this.formData.open_type == 1) {
                // 单张
                pack = {
                  code: 21,
                  data: {
                    authLimitAmount: this.formData.chargeMoney, //充值金额-最小10
                    cardAlias: this.formData.cardAlias || '无持卡人', //选填,  卡片别名
                    binRangeId: this.formData.cardBin, //卡头
                  },
                }
                loading = this.$loading({
                  lock: true,
                  text: '开卡中',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)',
                })
              } else {
                // 批量
                pack = {
                  code: 22,
                  data: {
                    unique: this.formData.unique,
                    binRangeId: this.formData.cardBin, //卡头
                  },
                }
              }
            } else {
              // 有持卡人
              if (this.formData.open_type == 1) {
                let obj = {}
                ;[
                  'firstName',
                  'lastName',
                  'mobile',
                  'billingAddress',
                  //"address2",
                  'billingCity',
                  'billingState',
                  'billingZipCode',
                  'label',
                  'cardBin',
                ].forEach((item) => {
                  obj[item] = this.formData[item]
                })
                obj = {
                  ...obj,
                  authLimitAmount: this.formData.chargeMoney, //充值金额-最小10
                  binRangeId: '404038', //卡头
                }
                // list = [obj]
                // num = this.formData.num;
                pack = {
                  code: 25,
                  data: obj,
                }
                loading = this.$loading({
                  lock: true,
                  text: '开卡中',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)',
                })
              } else {
                pack = {
                  code: 26,
                  data: {
                    unique: formData.unique,
                    binRangeId: this.formData.cardBin, //卡头
                  },
                }
              }
            }

            sendData(pack, () => {
              if (loading) {
                loading.close()
                this.toPage('/Horoscope-card/prepaidCard')
              }
            })
          }
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .horoscope-list {
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    margin-bottom: 20px;
    border-left: 4px solid #6b1ce9;
    .icon {
      margin-top: 4px;
      font-size: 18px;
      color: #000;
      cursor: pointer;
    }
  }
  .card-pay {
    span {
      display: inline-block;
      margin-right: 40px;
      font-size: 12px;
      color: #999;
    }
  }
  .span_block {
    display: inline-block;
    margin-right: 40px;
  }
  ::v-deep .el-input--small .el-input__inner {
    height: 40px;
  }
  ::v-deep .el-upload {
    width: 480px !important;
  }
</style>
